package com.zy.strategy.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zy.constant.AuthConstants;
import com.zy.domain.LoginSysUser;
import com.zy.mapper.LoginSysUserMapper;
import com.zy.model.SecurityUser;
import com.zy.strategy.LoginStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * '商城后台管理系统用户'登录策略的具体实现
 * 具体登录策略，通过@Service(AuthConstants.SYS_USER_LOGIN)存放至上下文中
 */
@Service(AuthConstants.SYS_USER_LOGIN)
public class SysUserLoginStrategy implements LoginStrategy {

    @Autowired
    private LoginSysUserMapper loginSysUserMapper;

    @Override
    public UserDetails realLogin(String username) {
        //根据用户名查询用户
        LoginSysUser loginSysUser = loginSysUserMapper.selectOne(new LambdaQueryWrapper<LoginSysUser>()
                .eq(LoginSysUser::getUsername, username)
        );
        /*LoginSysUser loginSysUser = loginSysUserMapper.selectOne(new QueryWrapper<LoginSysUser>()
                .eq("username", username)
        );*/
        //判断用户是否为空
        if (ObjectUtil.isNotNull(loginSysUser)) {
            //根据用户标识查询用户的权限集合
            //由于查出来的perms可能会有重复的，若使用distinct关键字在sql层面实现去重可能会导致索引失效
            //因此采用Set集合接收，无序不可重复
            Set<String> perms = loginSysUserMapper.selectPermsByUserId(loginSysUser.getUserId());

            //用户信息写入SecurityUser，Security只能识别SecurityUser对象
            SecurityUser securityUser = new SecurityUser();
            securityUser.setUserId(loginSysUser.getUserId());
            securityUser.setLoginType(AuthConstants.LOGIN_TYPE);//通过loginType区分用户，再结合userId可实现唯一性
            securityUser.setPassword(loginSysUser.getPassword());
            securityUser.setStatus(loginSysUser.getStatus());
            securityUser.setShopId(loginSysUser.getShopId());

            //判断用户权限集合是否为空
            if (CollectionUtil.isNotEmpty(perms) && perms.size()!=0) {
                securityUser.setPerms(perms);
            }

            //用户认证信息写入Security上下文
            return securityUser;
        }
        return null;
    }
}
